package com.github.vortexdev.yachtclub.repository.mysql;

import com.github.vortexdev.yachtclub.models.Regatta;
import com.github.vortexdev.yachtclub.models.Yacht;
import com.github.vortexdev.yachtclub.repository.RegattaRepository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Sergey Parakhin (sergey.parahin@gmail.com)
 */
public class MysqlRegattaRepository implements RegattaRepository {
    private JdbcTemplate jdbcTemplate;

    private static final String SELECT_ALL_SQL_TEMPLATE = "SELECT * FROM regatta;";
    private static final String SELECT_ALL_BY_YACHT_SQL_TEMPLATE = "SELECT regatta.*"
            + "FROM regatta, regatta_participants "
            + "WHERE regatta.regattaId = regatta_participants.regattaId AND "
            + "regatta_participants.yachtId = ?;";

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public List<Regatta> findAll() {
        return jdbcTemplate.query(SELECT_ALL_SQL_TEMPLATE, REGATTA_MAPPER);
    }

    @Override
    public List<Regatta> findByYacht(Yacht yacht) {
        return jdbcTemplate.query(
                SELECT_ALL_BY_YACHT_SQL_TEMPLATE,
                new Object[]{yacht.getYachtId()},
                REGATTA_MAPPER
        );
    }

    private static final RowMapper<Regatta> REGATTA_MAPPER = new RowMapper<Regatta>() {
        public Regatta mapRow(ResultSet rs, int rowNum) throws SQLException {
            Regatta regatta = new Regatta();
            regatta.setRegattaId(rs.getInt("regattaId"));
            regatta.setName(rs.getString("name"));
            regatta.setCountry(rs.getString("country"));
            regatta.setCity(rs.getString("city"));
            regatta.setRegattaDate(null);
            return regatta;
        }
    };
}
